package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    //code 换取openid
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code  ";
    //获取手机号
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    //获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token ";
    //根据code获取openid
    private static final String appId = "wx7ef4124b69038aff";
    private static final String secret = "44381c500a128374ab665f5eb8405576";
    @Override
    public String getOpenId(String code) {
        //封装请求参数
        Map<String,Object> map = getAppConfig();
        map.put("js_code",code);
        String s = HttpUtil.get(REQUEST_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        if (jsonObject.get("openid") != null) {
            return jsonObject.getStr("openid");
        }
        return null;
    }
    private Map<String, Object> getAppConfig() {

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid",appId);
        requestUrlParam.put("secret",secret);
        return requestUrlParam;
    }
    @Override
    public String getPhoneCode(String code) {
        String token = getToken();
        String url = PHONE_URL +token;
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        String post = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(post);
        if (jsonObject.get("phone_info") != null) {
            JSONObject phone_info = (JSONObject) jsonObject.get("phone_info");
            return phone_info.getStr("phoneNumber");
        }
        return null;
    }

    public String getToken() {
        Map<String,Object> map = getAppConfig();
        map.put("grant_type","client_credential");
        String s = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        if (jsonObject.get("access_token") != null) {
            return jsonObject.getStr("access_token");
        }
        return null;
    }
}
